package com.qingzhou.web.controller.system;

import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import com.qingzhou.common.utils.ExcelUtil;
import com.qingzhou.common.web.controller.BaseController;
import com.qingzhou.common.web.domain.PageData;
import com.qingzhou.system.domain.SysLoginLog;
import com.qingzhou.system.service.ISysLoginLogService;
import org.noear.solon.annotation.*;
import org.noear.solon.auth.annotation.AuthPermissions;
import org.noear.solon.core.handle.Result;

import java.util.Arrays;
import java.util.List;

/**
 * 系统访问记录 操作处理
 * @author xm
 */
@Controller
@Mapping("system/loginlog")
public class SysLoginLogController extends BaseController {

    @Inject
    ISysLoginLogService sysLoginLogService;

    /**
     * 查询登录日志列表
     */
    @AuthPermissions("system:loginlog:list")
    @Get
    @Mapping("list")
    public PageData list(Page<SysLoginLog> page, SysLoginLog sysLoginLog) {
        QueryWrapper qw = getQW(sysLoginLog);
        Page<SysLoginLog> result = sysLoginLogService.page(page, qw);
        return getPageData(result);
    }

    /**
     * 导出登录日志列表
     */
    @AuthPermissions("system:loginlog:export")
    @Post
    @Mapping("export")
    public void export(SysLoginLog sysLoginLog) {
        QueryWrapper qw = getQW(sysLoginLog);
        List<SysLoginLog> list = sysLoginLogService.list(qw);
        ExcelUtil.export(list);
    }

    /**
     * 解锁用户登录状态
     */
    @AuthPermissions("system:loginlog:unlock")
    @Get
    @Mapping("unlock/{userName}")
    public Result unlock(@Path String userName) {
        sysLoginLogService.unlock(userName);
        return Result.succeed();
    }

    /**
     * 删除登录日志
     */
    @AuthPermissions("system:loginlog:remove")
    @Delete
    @Mapping("{infoIds}")
    public Result remove(@Path String[] infoIds) {
        return toResult(sysLoginLogService.removeByIds(Arrays.asList(infoIds)));
    }

    /**
     * 清空登录日志
     */
    @AuthPermissions("system:loginlog:remove")
    @Delete
    @Mapping("clean")
    public Result clean() {
        sysLoginLogService.clean();
        return Result.succeed();
    }

    private QueryWrapper getQW(SysLoginLog sysLoginLog) {
        QueryWrapper qw = QueryWrapper.create();
        qw.and(SysLoginLog::getIpaddr).like(sysLoginLog.getIpaddr());
        qw.and(SysLoginLog::getUserName).like(sysLoginLog.getUserName());
        qw.and(SysLoginLog::getStatus).eq(sysLoginLog.getStatus());
        qw.and(SysLoginLog::getCreateTime).ge(sysLoginLog.getStartTime());
        qw.and(SysLoginLog::getCreateTime).le(sysLoginLog.getEndTime());
        qw.orderBy(SysLoginLog::getCreateTime).desc();
        return qw;
    }

}
